/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.rzt.cft.utils;

import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.entity.sys.SysUser;
import com.rzt.cft.exception.CustomException;
import com.rzt.cft.service.sys.ISysUserService;
import com.rzt.cft.dto.sys.SysUserDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.UUID;

/**
 * Shiro工具类
 *
 * @author zhongzhong
 * @date 2019年12月30日 上午9:49:19
 */
@Slf4j
public class ShiroUtils {

    /**
     * 加密算法
     */
    public final static String HASH_ALGORITHM_NAME = "SHA-256";

    /**
     * 循环次数
     */
    public final static int HASH_ITERATIONS = 16;

    public static String sha256(String password, String salt) {
        return new SimpleHash(HASH_ALGORITHM_NAME, password, salt, HASH_ITERATIONS).toString();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new CustomException(ServiceStatus.VERIFICATION_CODE_INVALID);
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

    /**
     * 兼容jwt和常规开发时获取用户信息
     *
     * @return
     */
    public static SysUserDto getSysUser() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Object principal = subject.getPrincipal();
            if (principal instanceof String) {
                String token = (String) principal;
                Integer userId = JwtUtil.getUserId(token);
                SysUserDto userDto = CustomUtil.maping(SpringContextHolder.getBean(ISysUserService.class).getById(userId), SysUserDto.class);
                return userDto;
            } else if (principal instanceof SysUser) {
                return CustomUtil.maping(principal, SysUserDto.class);
            }
        } catch (Exception ignore) {
            log.error("getSysUser 获取用户信息错误:{}", ignore);
        }
        return null;
    }

    public static String getUserId() {
        SysUserDto sysUser = getSysUser();
        return sysUser == null ? null : sysUser.getId();
    }

    public static String getSalt() {
        return get(true);
    }

    public static String get(boolean isPureStr) {
        String sesult = UUID.randomUUID().toString();
        if (isPureStr) {
            sesult = sesult.replaceAll("-", "");
        }
        return sesult;
    }

}
